// API配置
const BASE_URL = 'http://localhost:3000/api'

function request(options) {
  return new Promise((resolve, reject) => {
    const token = uni.getStorageSync('token')
    if (token) {
      options.header = {
        ...options.header,
        'Authorization': `Bearer ${token}`
      }
    }

    console.log(`发送${options.method || 'GET'}请求到: ${BASE_URL + options.url}`, options.data)
    
    // 确保data中没有undefined值
    const cleanData = options.data ? JSON.parse(JSON.stringify(options.data)) : {}
    
    uni.request({
      url: BASE_URL + options.url,
      method: options.method || 'GET',
      data: cleanData,
      header: {
        'Content-Type': 'application/json',
        ...options.header
      },
      success: (res) => {
        console.log(`请求成功，状态码: ${res.statusCode}`, res.data)
        if (res.statusCode === 200) {
          resolve(res.data)
        } else {
          console.error(`请求失败，状态码: ${res.statusCode}`, res.data)
          reject(res.data)
        }
      },
      fail: (err) => {
        console.error('请求失败:', err)
        reject(err)
      }
    })
  })
}

export const api = {
  user: {
    getProfile() {
      return request({
        url: '/users/profile',
        method: 'GET'
      })
    },
    updateProfile(data) {
      return request({
        url: '/users/profile',
        method: 'PUT',
        data
      })
    }
  },
  music: {
    getFavorites() {
      return request({
        url: '/music/favorites',
        method: 'GET'
      })
    },
    getHistory() {
      return request({
        url: '/music/history',
        method: 'GET'
      })
    },
    getSongDetail(songId) {
      return request({
        url: `/music/song/${songId}`,
        method: 'GET'
      })
    }
  }
}